import { keepEdge } from "laya-system";
import { System } from "laya-system";
import { Gun } from "../BulletSystem/Gun";
export default class Player {
    text: Laya.Text;
    RigidBody!: Laya.RigidBody;
    player: Laya.Sprite;
    gun!: Gun;
    constructor(prefab: Laya.Prefab) {
        this.player = prefab.create();
        this.text = this.player.getChildByName("text") as Laya.Text;
        this.RigidBody = this.player.getComponent(
            Laya.RigidBody
        ) as Laya.RigidBody;
    }

    useGun(prefab: Laya.Prefab, MapSprite: Laya.Sprite = Laya.stage) {
        this.gun = new Gun(this.player, prefab);
        this.gun.handleClick(MapSprite);
    }

    updatePositionTips() {
        // this.text.text =
        //     Math.ceil(this.player.x) + " " + Math.ceil(this.player.y);
    }
    placeToStage([x, y]: [number, number], MatrixBorder: [number, number]) {
        // console.log(x, y);
        this.player.pos(x, y);
        this.player.zOrder = 100;

        this.player.timer.frameLoop(5, this, () => {
            this.updatePositionTips();
            this.keepInStage(MatrixBorder);
        });
    }
    keepInStage([maxX, maxY]: [number, number]) {
        // 将整个对象约束在这个方格内
        keepEdge(
            this.player,
            {
                minX: 0,
                minY: 0,
                maxX,
                maxY,
            },
            () => {
                // 反向赋值速度
                this.RigidBody.setVelocity({
                    x: -this.RigidBody.linearVelocity.x * 0.1,
                    y: -this.RigidBody.linearVelocity.y * 0.1,
                });
            }
        );
    }
    jumping = false;

    // ! 下面为键盘控制
    InitKeyBind() {
        const RigidBody = this.RigidBody;
        console.log(RigidBody);
        System.Keybind.setEvents([
            [
                [Laya.Keyboard.W],
                () => {
                    if (!this.jumping) {
                        RigidBody.setVelocity({
                            x: RigidBody.linearVelocity.x,
                            y: -10,
                        });
                        // this.jumping = true;
                        this.jumping = false;
                    }
                },
            ],
            [
                [Laya.Keyboard.D],
                () => {
                    RigidBody.setVelocity({
                        x: 10,
                        y: RigidBody.linearVelocity.y,
                    });
                },
            ],
            [
                [Laya.Keyboard.A],
                () => {
                    RigidBody.setVelocity({
                        x: -10,
                        y: RigidBody.linearVelocity.y,
                    });
                },
            ],
        ]);
    }
}
